<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称进行查询" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
	  <el-form-item label="位置" prop="app">
	    <el-select v-model="queryParams.app" placeholder="位置" clearable size="small" style="width: 240px">
	      <el-option label="小程序" value="1" />
	      <el-option label="网站" value="2" />
	    </el-select>
	  </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable size="small" style="width: 240px">
          <el-option label="上架" value="1" />
          <el-option label="下架" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['cms:banner:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['cms:banner:remove']">删除</el-button>
      </el-col> -->
      <div class="top-right-btn">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
            <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
          </el-tooltip>
        </div>
      </el-row>
    </el-row>

    <el-table v-loading="loading" :data="startpageList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="位置" align="center" prop="location" :formatter="locationFormat" />
      <el-table-column label="图片" align="center" prop="imgUrl" >
        <template slot-scope="scope">
        <el-image style="width: 60px; height: 40px"
          :src="scope.row.imgUrl">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        </template>
      </el-table-column>
      <el-table-column label="上下架" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="2"
            @change="handleUseFlagChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['cms:banner:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['cms:banner:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改banner对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入前置页名称" />
        </el-form-item>
        <el-form-item label="位置" prop="app">
          <el-radio-group v-model="form.app">
            <el-radio :label="1">小程序</el-radio>
            <el-radio :label="2">网站</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架" prop="status">
          <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="2" >
          </el-switch>
        </el-form-item>
        <el-form-item label="图片" prop="imgUrl" required>
          <el-upload ref="imgUrl"
              action="#"
              :http-request="requestUpload"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :multiple="false"
              :limit="1"
              :on-exceed="handleExceed"
              list-type="picture">
            <el-button size="small">
              上传
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            <div slot="tip" class="el-upload__tip">只能上传图片</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listStartpage,
    getStartpage,
    delStartpage,
    addStartpage,
    updateStartpage,
    changeStatus
  } from "@/api/cms/startpage";
  import {
    upload
  } from "@/api/upload.js"

  export default {
    name: "Startpage",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // banner表格数据
        startpageList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // banner位置，枚举字典
        fileList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        // 表单参数
        form: {
          app: 1,
          status: 1,
          imgUrl: ''
        },
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }],
          imgUrl: [{
            required: true,
            message: "图片不能为空",
            trigger: "blur"
          }],
          app: [{
            required: true,
            message: "位置不能为空",
            trigger: "blur"
          }],
          status: [{
            required: true,
            message: "是否上架不能为空",
            trigger: "blur"
          }]
        },
        //上传路径
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload"
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询banner列表 */
      getList() {
        this.loading = true;
        listStartpage(this.queryParams).then(response => {
          this.startpageList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // banner位置，枚举字典翻译
      locationFormat(row, column) {
        if(row.app == 1)
          return "小程序";
        else
          return "官网";
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          name: undefined,
          app: 1,
          imgUrl: undefined,
          status: 1
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加前置页";
        this.fileList = [];
        this.form.status=1;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.fileList = [];
        const id = row.id || this.ids
        getStartpage(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改前置页";
          if(response.data.imgUrl != null && response.data.imgUrl != ''){
            let urlArr = response.data.imgUrl.split("/");
            this.fileList = [{name:urlArr[urlArr.length-1],url:response.data.imgUrl}];
          }
        });
      },
      // 上下架修改
      handleUseFlagChange(row) {
        let text = row.status === 2 ? "下架" : "上架";
        this.$confirm('确认要"' + text + '""' + row.name + '"前置页吗?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
            return changeStatus(row.id);
          }).then(() => {
            this.msgSuccess(text + "成功");
            this.getList();
          }).catch(function() {
            row.status = row.status === 2 ? 1 : 2;
          });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateStartpage(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                  this.fileList = [];
                }
              });
            } else {
              addStartpage(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                  this.fileList = [];
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除前置页编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStartpage(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      beforeUpload(file) {
        const isJPG = file.type.indexOf("image/") != -1;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      requestUpload(params){
        const file = params.file;

        let formData = new FormData();
        formData.append("file", file);
        formData.append("fileSavePath","/cms/startpage");

        upload(formData).then(response => {
          if (response.code === 200) {
            this.form.imgUrl = response.url;
            // this.fileList = [{name:response.fileName, url: response.url}];
          }else{
            this.$message.error('上传图片失败！');
          }
        });
      },
      handleRemove(file, fileList) {
        this.form.imgUrl = '';
      },
      handleExceed(files, fileList){
        this.$message.error('只能上传一张图片!');
      }
    }
  };
</script>
